package com.yl.zqy.service.impl.sys.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.yl.zqy.dto.excel.SysUserTemplateExportDTO;
import com.yl.zqy.entity.sys.SysDept;
import com.yl.zqy.entity.sys.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 用户导入监听器
 * @Author liang.yu
 * @Date 2024/4/18 21:00
 */
@Slf4j
public class SysUserTemplateExportDTOReadListener implements ReadListener<SysUserTemplateExportDTO> {
    protected final long startTime = System.nanoTime();
    /**
     * 缓存的数据
     */
    private final List<SysUser> cachedDataList;
    private final Map<String, String> deptMap;

    public SysUserTemplateExportDTOReadListener(List<SysUser> list, List<SysDept> deptList) {
        this.cachedDataList = list;
        this.deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getName, SysDept::getId));
    }

    @Override
    public void invoke(SysUserTemplateExportDTO sysUserTemplateExportDTO, AnalysisContext analysisContext) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUserTemplateExportDTO,user);
        user.setDeptId(deptMap.get(sysUserTemplateExportDTO.getDeptName()));
        cachedDataList.add(user);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("解析用户excel导入数据耗时：{}", Duration.ofNanos(System.nanoTime() - startTime).toString().substring(2));
    }
}
